#include "DisplayStream.h"

DisplayStream::DisplayStream(cv::VideoCapture &streamSource) : streamSource(streamSource)
{
	this->record = false;
}

void DisplayStream::Record(FILE *file, cv::Mat &camFrame)
{
	/*Rgb => YUV 4-4-4 => 4-1-1*/
	cv::Mat yuv444 = this->RGB2YUV->ConvertRgbToYuv(camFrame);
	
	cv::Mat yuv411 =  this->RGB2YUV->ConvertYUV_444_To_411(yuv444);	
	
	DCT_ENCODED *tab = this->dctCompress->DCTEncode(yuv411);
}

void DisplayStream::Read(FILE *file)
{
	this->RGB2YUV = new RGBtoYUV();
	this->dctCompress = new DctCompression(file);

	int key = 0;
	
	while (	key != 27)
	{
		key = cv::waitKey(100);
		cv::Mat img = this->dctCompress->DCTUnencode();
		img = RGB2YUV->ConvertYuv411ToRgb(img, img.size().width, img.size().height);
		imshow("Display YUV to RGB", img);
	}
	delete this->dctCompress;
	delete this->RGB2YUV;
 }

DWORD DisplayStream::Run()
{
	this->status = VideoStatus::PLAY;
	int key = -1;
	cv::Mat cameraFrame;
	FILE *file;

	while (key != 27)
	{
		//Read frame
		this->streamSource.read(cameraFrame);
		imshow("Display origi", cameraFrame);
		key = cv::waitKey(10);
		if (key == 32)
			this->status = this->status == VideoStatus::PLAY ? VideoStatus::PAUSE : VideoStatus::PLAY;
		if (key == 'd')
		{
			this->status = VideoStatus::PLAY;
			listImg.clear();
		}
		if (key == 'r')
		{
			this->record  = !this->record;
			if (record)
			{
				file = fopen("MyVideo.km", "wb+");
				this->RGB2YUV = new RGBtoYUV();
				this->dctCompress = new DctCompression(file, cameraFrame.size().width,  cameraFrame.size().height, cameraFrame.type());
			}
			else
			{
				fclose(file);
				delete this->dctCompress;
				delete this->RGB2YUV;
			}
		}
		if (record)
			this->Record(file, cameraFrame);
	}
	file = fopen("MyVideo.km", "rb");
	this->Read(file);
	fclose(file);

	return 0;
}
